<script>
// NEW TAB/REFRESH 0
// CLOSE TAB 1
// CHANGE SELECTED 2
var SEP = ",";

function isChromeTab(url) {
    sub = url.substring(0, 9);
    if (sub == "chrome://") return 1;
    else return 0;
}

function getTime() {
    var now = new Date();
    return now.getTime();
    //var ret = (now.getMonth()+1) + "/" + now.getDate() + "/" + now.getFullYear() + now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds();
    //return ret;
}

chrome.extension.onRequest.addListener(
    function(request, sender, sendResponse) {
        chrome.tabs.getSelected(null, 
            function(tab) {
                //if (isChromeTab(tab.url)) return;
                var key = getTime() + SEP + tab.id + SEP + tab.url;
                setItem(key, 0); // 0: NEW TAB/REFRESH 
                console.info("insertion complete");
                var ivalue = getItem(key);
                console.info("fetching info");
                console.info("Time Record: " + key);
                console.info("Status:" + ivalue);
            });
    });

chrome.tabs.onSelectionChanged.addListener(
    function(tabId) {
        chrome.tabs.getSelected(null,
            function(tab) {
                //if (isChromeTab(tab.url)) return;
                var key = getTime() + SEP + tab.id + SEP + tab.url;
                setItem(key, 2); // 2: CHANGE SELECTED
                console.info("insertion complete");
                var ivalue = getItem(key);
                console.info("fetching info");
                console.info("Time Record: " + key);
                console.info("Status:" + ivalue);
            });
    });

chrome.tabs.onRemoved.addListener(
    function(tabId) {
        var key = getTime() + SEP + tabId;
        setItem(key, 1); // 1: TAB CLOSED
        console.info("insertion complete");
        var ivalue = getItem(key);
        console.info("fetching info");
        console.info("Time Record: " + key);
        console.info("Status:" + ivalue);
    });

function setItem(key, value) {
    try {
        console.info("Insert key:value");
        window.localStorage.removeItem(key);
        window.localStorage.setItem(key, value);
    } catch (e) {
        console.info("Error setItem inside");
        console.info(e)
    }
}

function getItem(key) {
    var value;
    //console.info("Get key: " + key);
    try {
        value = window.localStorage.getItem(key);
    } catch (e) {
        console.info("Error getItem inside")
    }
    return value
}

function getSize() {
    return window.localStorage.length;
}

function getKey(id) {
    return window.localStorage.key(id);
}

function cleanStorage() {
    window.localStorage.clear();
}

</script>
